/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wii.elpro.dao.jpa;

import com.wii.elpro.dao.JPAUtil;
import com.wii.elpro.dao.ProdukDAOInterface;
import com.wii.elpro.entity.Produk;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author hendro
 */
public class ProdukDAOImpl extends DAOGenericImpl implements ProdukDAOInterface {

    public Produk getProduk(long id) throws Exception {
        JPAUtil.beginTransaction();
        EntityManager em = JPAUtil.getEntityManager();
        try {
            return em.find(Produk.class, id);
        } catch (Exception ex) {
            throw ex;
        }
    }

    public List<Produk> getProduks() throws Exception {
        JPAUtil.beginTransaction();
        EntityManager em = JPAUtil.getEntityManager();
        try {
            return em.createQuery("SELECT p FROM Produk p").getResultList();
        } catch (Exception ex) {
            throw ex;
        }
    }

    public List<Produk> getProduksByName(String pName) throws Exception {
        JPAUtil.beginTransaction();
        EntityManager em = JPAUtil.getEntityManager();
        try {
            return em.createQuery("SELECT p FROM Produk p WHERE p.nama LIKE ?").setParameter(0, '%' + pName + '%').getResultList();
        } catch (Exception ex) {
            throw ex;
        }
    }

    public List<Produk> getProduksByKode(String pKode) throws Exception {
        JPAUtil.beginTransaction();
        EntityManager em = JPAUtil.getEntityManager();
        try {
            return em.createQuery("SELECT p FROM Produk p WHERE p.kode LIKE ?").setParameter(0, '%' + pKode + '%').getResultList();
        } catch (Exception ex) {
            throw ex;
        }
    }

    public boolean kodeIsUsed(String pKode) throws Exception {
        JPAUtil.beginTransaction();
        EntityManager em = JPAUtil.getEntityManager();
        Produk produk = null;
        boolean isUsed = false;
        try {
            produk = (Produk) em.createQuery("SELECT p FROM Produk p WHERE p.kode=:input").setParameter("input", pKode).getResultList();
        } catch (Exception ex) {
            throw ex;
        }
        if (produk != null) {
            isUsed = true;
        } else {
            isUsed = false;
        }
        return isUsed;
    }
}
